import { connect } from 'umi';
import { DatePicker, Select, Button } from 'antd';
import TradeCenterTime from '../TradeCenterTime';
import styles from './index.less';
import { useEffect, useState } from 'react';
import { useDebounceFn } from 'ahooks';
import moment from 'moment';
import { getStation } from '../../utils';

const Header = ({
  tradeCenterTime,
  marketList,
  marketId,
  tradeDate,
  originStations,
  stations,
  convertResultTreeData,
  declareList,
  dispatch,
  stationId,
  headerLoading,
}) => {
  const [marketValue, setMarketValue] = useState();
  const [stationList, setStationList] = useState([]);
  const [stationIdValue, setStationIdValue] = useState();

  const getOptions = (data, marketId) => {
    const market = data.find((item) => item.key === marketId);
    if (!market) return [];
    return (
      market.children?.flatMap(
        (category) =>
          category.children?.map((child) => ({
            label: child.title,
            value: child.key,
          })) || [],
      ) || []
    );
  };

  const handleSearch = () => {
    let stations = originStations.filter((item) => {
      return item.marketId === marketId;
    });
    if (stationIdValue === undefined || stationIdValue === null) {
      setStationIdValue(stations[0]?.value);
    }
    dispatch({
      type: 'dayRollingTradeStragety/setStations',
      payload: stations,
    });
    const params = {
      stationId: stationId || stations[0]?.value,
      marketId,
      date: tradeDate.format('YYYY-MM-DD'),
    };

    dispatch({
      type: 'dayRollingTradeStragety/fetchSequencesEffect',
      payload: params,
    });

    dispatch({
      type: 'dayRollingTradeStragety/setSearchStationId',
      payload: stationIdValue || stations[0]?.value,
    });
  };

  const handleXJSearch = () => {
    dispatch({
      type: 'dayRollingTradeStragety/fetchXJDataEffect',
      payload:
        marketValue != null ? marketValue : getOptions(convertResultTreeData, 'PXBXJ')[0]?.value,
    });
  };

  const handleNxSearch = () => {
    dispatch({
      type: 'dayRollingTradeStragety/setNxRefresh',
      payload: moment().valueOf().toString(),
    });
  };

  const searchFn = useDebounceFn(
    () => {
      if (marketId === 'PXBXJ') {
        handleXJSearch();
      } else if (marketId === 'PXBNX') {
        handleNxSearch();
      } else {
        handleSearch();
      }
    },
    { wait: 500 },
  );

  const onChangeMarket = (value) => {
    // 目前只针对宁夏其他为老逻辑
    if (value === 'PXBNX') {
      const stations = getStation(marketList, value);
      const first = stations[0];
      setStationList(stations);
      dispatch({
        type: 'dayRollingTradeStragety/setStationId',
        payload: first.value,
      });
      dispatch({
        type: 'dayRollingTradeStragety/setNxRefresh',
        payload: moment().valueOf().toString(),
      });
    }
  };

  const changeStation = (value) => {
    dispatch({
      type: 'dayRollingTradeStragety/setStationId',
      payload: value,
    });
  };

  const changeStationSX = (value) => {
    dispatch({
      type: 'dayRollingTradeStragety/setStationId',
      payload: value,
    });
    setStationIdValue(value);
  };

  const onDateChange = (tradeDate) => {
    dispatch({
      type: 'dayRollingTradeStragety/setTradeDate',
      payload: tradeDate,
    });
  };

  const _onReset = useDebounceFn(
    () => {
      const firstMarket = marketList[0];
      if (firstMarket.value === 'PXBNX') {
        onDateChange(moment());
        onChangeMarket(firstMarket.value);
      } else {
        dispatch({
          type: 'dayRollingTradeStragety/setMarketId',
          payload: firstMarket.value,
        });
        dispatch({
          type: 'dayRollingTradeStragety/setProvinceId',
          payload: firstMarket.provinceId,
        });
        onDateChange(moment());
        handleSearch();
        setMarketValue();
        setStationIdValue(stations[0]?.value);
      }
    },
    { wait: 500 },
  );

  useEffect(() => {
    if (marketId) {
      dispatch({
        type: 'dayRollingTradeStragety/setNxRefresh',
        payload: undefined,
      });
      if (marketId === 'PXBXJ') {
        dispatch({
          type: 'dayRollingTradeStragety/setConvertResultTreeData',
          payload: originStations,
        });
        handleXJSearch();
      } else if (marketId === 'PHBSX') {
        handleSearch();
      } else {
        // 通用逻辑
        onChangeMarket(marketId);
      }
    }
  }, [marketId, originStations]);

  return (
    <div className={styles.header}>
      <div className={styles.condition}>
        <Select
          className={styles.provinceSelect}
          value={marketId}
          options={marketList}
          onChange={(value, opt) => {
            dispatch({
              type: 'dayRollingTradeStragety/setProvinceId',
              payload: opt.provinceId,
            });
            dispatch({
              type: 'dayRollingTradeStragety/setMarketId',
              payload: value,
            });
          }}
        />
        {marketId === 'PHBSX' ? (
          <Select
            className={styles.stationSelect}
            // showSearch
            // optionFilterProp="children"
            value={stationIdValue}
            onChange={changeStationSX}
          >
            {stations.map((item) => {
              return (
                <Select.Option value={item.value} key={item.value}>
                  {item.label}
                </Select.Option>
              );
            })}
          </Select>
        ) : null}
        {convertResultTreeData && marketId === 'PXBXJ' ? (
          <div className={styles.marketSelect}>
            <Select
              value={
                marketValue != null
                  ? marketValue
                  : getOptions(convertResultTreeData, 'PXBXJ')[0]?.value
              }
              style={{
                width: 166,
              }}
              onChange={(value) => {
                setMarketValue(value);
              }}
              options={getOptions(convertResultTreeData, 'PXBXJ')}
            />
          </div>
        ) : null}
        {marketList && marketId === 'PXBNX' ? (
          <div className={styles.marketSelect}>
            <Select
              value={stationId ? stationId : undefined}
              style={{
                width: 166,
              }}
              onChange={changeStation}
              options={stationList}
            />
          </div>
        ) : null}

        <DatePicker
          className={styles.dataPicker}
          allowClear={false}
          onChange={onDateChange}
          value={tradeDate}
          format="YYYYMMDD"
          style={{ width: 180 }}
        />
        <Button
          className={styles.queryBtn}
          type="primary"
          // onClick={marketId === 'PXBXJ' ? handleXJSearch : handleSearch}
          onClick={searchFn.run}
          loading={headerLoading}
        >
          查询
        </Button>
        <Button
          className={styles.reset}
          htmlType="reset"
          onClick={_onReset.run}
          ghost
          loading={headerLoading}
        >
          重置
        </Button>
      </div>
      {/* {tradeCenterTime ? <TradeCenterTime /> : <div />} */}
      <div />
    </div>
  );
};

export default connect(({ dayRollingTradeStragety }) => ({
  tradeCenterTime: dayRollingTradeStragety.tradeCenterTime,
  marketList: dayRollingTradeStragety.marketList,
  marketId: dayRollingTradeStragety.marketId,
  tradeDate: dayRollingTradeStragety.tradeDate,
  originStations: dayRollingTradeStragety.originStations,
  stations: dayRollingTradeStragety.stations,
  convertResultTreeData: dayRollingTradeStragety.convertResultTreeData,
  declareList: dayRollingTradeStragety.declareList,
  stationId: dayRollingTradeStragety.stationId,
  headerLoading: dayRollingTradeStragety.headerLoading,
}))(Header);
